/* ohai
 *
 * ohai acts as a write(1) replacement, and sends messages via ohaigent.
 *
 * Copyright 2008 Cian Synnott.
 * 
 *$Id: ohai.c 28 2009-12-04 03:01:17Z cian $
 */
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "log.h"
#include "utility.h"
#include "version.h"

static struct option longopts[] = {
  { "debug", no_argument, 0, 'D' },
  { "help", no_argument, 0, 'h' },
  { "version", no_argument, 0, 'V' },
  { 0, 0, 0, 0 }
};

static char *shortopts = "DhV";

static void usage(void) {
  puts("Usage: ohai [OPTIONS] user@host/resource\n"
    "write(1) replacement for 'ohai', the jabber/xmpp commandline suite.\n"
    " -d, --debug        Be verbose in logging.\n"
    " -h, --help         Print this text.\n"
    " -V, --version      Print the version.\n"
    "See the project page at http://code.google.com/p/ohai/");
}

int main(int argc, char *argv[]) {
  char *text = NULL;
  char *command = NULL;
  size_t size = 0;
  int opt;
  int fd;
  size_t len;

  while ((opt = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
    switch(opt) {
      case 'D':
        log_set_debug();
        break;
      case 'h':
        usage();
        exit(EXIT_SUCCESS);
        break;
      case 'V':
        puts("ohai " OHAI_VERSION);
        exit(EXIT_SUCCESS);
    }
  }

  if (argc - optind != 1) {
    usage();
    exit(EXIT_FAILURE);
  }

  if (getdelim(&text, &size, 0, stdin) == -1)
    log_errx(EXIT_FAILURE, "error calling getdelim: %s", strerror(errno));

  if ((command = calloc(8 + strlen(argv[optind]) + strlen(text), sizeof(char))) == NULL)
    log_errx(EXIT_FAILURE, "error allocating command buffer: %s", strerror(errno));

  sprintf(command, "SEND %s %s", argv[optind], text); 

  fd = connect_to_ohaigent(0);

  if ((len = write(fd, command, strlen(command))) == -1)
    log_errx(EXIT_FAILURE, "writing to UNIX socket %d: %s", fd, strerror(errno));

  if (len != strlen(command))
    log_warn("wrote only %d of %d bytes to UNIX socket %d", len, strlen(command), fd);

  if (close(fd) == -1)
    log_errx(EXIT_FAILURE, "closing UNIX socket %d: %s", fd, strerror(errno));

  return 0;
}
